import com.tencent.tmm.knoi.annotation.KNExport
import com.tencent.tmm.knoi.jsbind.getJSFunction
import com.tencent.tmm.knoi.type.JSValue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

private val fileSelectChannel = Channel<List<String>>(1) // 容量为 1，避免堆积

suspend fun selectFile(): List<String> = withContext(Dispatchers.IO) {
    getJSFunction("fileSelect")?.invoke<JSValue>()
    fileSelectChannel.receive()
}

@KNExport
internal fun resultFileSelect(result: List<String>) {
    CoroutineScope(Dispatchers.IO).launch {
        fileSelectChannel.send(result)
    }
}